<template>
  <div ref="chartRef" class="chart" />
</template>
<script>
import initChart from './initChart'
export default {
  props: {
    initData: {
      type: [Array, Object],
      default: () => []
    },
    initChart: {
      type: Function,
      default: initChart
    }
  },
  data() {
    return {
      resizeHandler: null,
      chart: null
    }
  },
  watch: {
    initData: {
      handler: function() {
        this.$nextTick(() => {
          if (this.initData.length > 0 && Array.isArray(this.initData) || this.initData) {
            this.print()
          }
        })
      },
      deep: true
    }
  },
  mounted() {
    this.print()
  },
  destroy() {
    console.log('销毁')
    this.chart.dispose()
  },
  methods: {
    // 防抖函数
    debounce(func, wait, immediate) {
      let timeout, args, context, timestamp, result

      const later = function() {
        const last = +new Date() - timestamp
        if (last < wait && last > 0) {
          timeout = setTimeout(later, wait - last)
        } else {
          timeout = null
          if (!immediate) {
            result = func.apply(context, args)
            if (!timeout) context = args = null
          }
        }
      }

      return function() {
        context = this
        args = arguments
        timestamp = +new Date()

        if (immediate && !timeout) {
          result = func.apply(context, args)
          context = args = null
        }

        clearTimeout(timeout)
        timeout = setTimeout(later, wait)
        return result
      }
    },
    print() {
      this.chart = this.initChart(this.$refs.chartRef, this.initData, this)

      this.resizeHandler = this.debounce(() => {
        if (this.chart) {
          this.chart.resize()
          // this.$nextTick(() => {
          //   this.chart = this.initChart(this.$refs.chartRef, this.initData)
          //   // this.chart.resize()

          // console.log('~~~~~~~', this.chart)
          this.$emit('resize', this.chart)
          // })
        }
      }, 300)
      window.addEventListener('resize', this.resizeHandler)
      this.$emit('print', this.chart)
      return this.chart
    }
  }
}
</script>
<style>
    .chart {
        width: 100%;
        height: 100%;
    }
</style>
